<?php
/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2018/5/22
 * Time: 17:11
 */

namespace Hilaoyu\LaravelExtend\Providers;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Hilaoyu\LaravelExtend\Supports\SubApp;
use Illuminate\Support\Str;

class EnvSubAppRegisterServiceProvider extends ServiceProvider
{
    public function boot()
    {

        if($sub_app_path = $this->getEnvSubAppPath()){

            SubApp::registerCommands($sub_app_path . '/Commands', $this->getEnvSubAppNamespace() . '\\Commands');


            if (!app()->runningInConsole()) {
                SubApp::registerRoutes($sub_app_path . '/routes', $this->getEnvSubAppNamespace() . '\\Controllers', []);
            }

            if(is_dir($sub_app_path.'/views')){
                $this->loadViewsFrom($sub_app_path.'/views', $this->getEnv());
            }
        }
        //dd(app('router')->getRoutes()->getRoutesByName());
        //dd(array_keys(Artisan::all()));
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if($sub_app_path = $this->getEnvSubAppPath()) {
            SubApp::registerExtendConfig($sub_app_path, []);
            SubApp::registerProviders($sub_app_path);
            SubApp::registerGlobalFunction($sub_app_path);
        }

    }

    protected function getEnv(){
        return config('app.env','');
    }
    protected function getEnvSubAppPath(){
        if($_app_env = $this->getEnv()){
            $sub_app_path = app_path('SubApps/'.$_app_env);
            if(is_dir($sub_app_path)){
                return $sub_app_path;
            }
        }

        return null;
    }
    protected function getEnvSubAppNamespace(){

        if($_app_env = $this->getEnv()){

            return Str::finish(app()->getNamespace(), '\\') . 'SubApps\\'.$_app_env;
        }
        return null;
    }
}
